iT邦幫忙

2026 iThome 鐵人賽

DAY 5
0
Modern Web

現在就學C# 與 ASP.NET Core系列 第 5

Day 5|Operator 與 Condition:運算、比較與條件判斷

  • 分享至 

  • xImage
  •  

Day 4 我們學會建立不同型別的 Variable:

decimal price = 100.5m;
int quantity = 3;
bool isFilled = false;

現在我們已經可以把資料儲存在 Variable 中。

但真正的程式不只是「儲存資料」,還需要:

計算資料
   ↓
比較資料
   ↓
判斷條件
   ↓
決定要執行哪一段程式

例如:

訂單金額是多少?

數量是否大於 0?

市場是否開盤?

訂單是否合法?

這些都會用到今天的:

Operator(運算子)與 Condition(條件判斷)

透過 Operator 產生計算或判斷結果,再使用 Condition 決定程式要走哪一個流程。


1. Operator 與 Expression 是什麼?

Operator(運算子)用來對資料進行:

計算
比較
賦值
邏輯判斷

例如:

decimal price = 100.5m;
int quantity = 3;

decimal total = price * quantity;

其中:

*

就是乘法 Operator。

而:

price * quantity

則是一個 Expression(運算式)

Expression 可以先理解成:

可以經過計算並產生一個結果的程式碼。

例如:

price * quantity

會產生數值結果:

301.5

而:

quantity > 0

則會產生:

true
或
false

所以可以先建立這個概念:

資料
 ↓
Operator
 ↓
Expression
 ↓
產生結果

2. Arithmetic Operator:數值運算

Arithmetic Operator 用來進行數值計算。

Operator 用途
+ 加法
- 減法
* 乘法
/ 除法
% 餘數

例如:

int a = 10;
int b = 3;

Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);

結果:

13
7
30
3
1

整數除法

這裡要特別注意:

int result = 10 / 3;

Console.WriteLine(result);

結果:

3

因為兩邊都是 int

10 → int
3  → int

兩個 int 相除時,結果仍然是 int,因此不會保留小數部分。

如果需要小數結果:

double result = 10.0 / 3;

Console.WriteLine(result);

結果會接近:

3.333333...

因為:

10.0

double


% 餘數運算子

% 用來取得除法後的餘數。

例如:

int result = 10 % 3;

Console.WriteLine(result);

結果:

1

因為:

10 ÷ 3
↓
商 3
餘 1

一個常見用途是判斷奇數與偶數:

int number = 10;

bool isEven = number % 2 == 0;

如果:

number % 2

結果為:

0

代表這個數字是偶數。


3. Assignment Operator:賦值

= 是 Assignment Operator(賦值運算子)。

例如:

int quantity = 10;

代表:

把 10
↓
指派給
↓
quantity

Variable 建立後也可以重新賦值:

quantity = 20;

這時 quantity 的值就會從:

10

變成:

20

複合賦值運算子

例如:

int quantity = 10;

quantity = quantity + 5;

可以簡寫成:

quantity += 5;

常見的複合賦值:

寫法 等同於
a += 5 a = a + 5
a -= 5 a = a - 5
a *= 5 a = a * 5
a /= 5 a = a / 5

另外還有常見的遞增與遞減運算:

quantity++;
quantity--;

可以先理解成:

quantity++
→ quantity 增加 1

quantity--
→ quantity 減少 1

之後學習 Loop 時會經常看到。


4. Comparison Operator:比較資料

Comparison Operator 用來比較兩個值。

比較後的結果一定是:

bool
↓
true / false

常見的 Comparison Operator:

Operator 意義
== 等於
!= 不等於
> 大於
< 小於
>= 大於等於
<= 小於等於

例如:

decimal price = 100m;

Console.WriteLine(price > 50m);
Console.WriteLine(price == 100m);
Console.WriteLine(price != 100m);

結果:

True
True
False

因此:

price > 50m

是一個 Expression,它最後產生:

true

=== 不一樣

這兩個符號很容易混淆:

=
→ Assignment

==
→ Comparison

例如:

int quantity = 10;

代表:

10 指派給 quantity

而:

quantity == 10

代表:

比較 quantity 是否等於 10

結果會是:

true

所以一定要記住:

=** 是賦值,== 是比較。**


5. Logical Operator:組合多個條件

當程式需要同時判斷多個條件時,可以使用 Logical Operator。

Operator 意義
&& AND
` OR
! NOT

&& AND

&& 代表:

所有條件都必須成立。

例如:

decimal price = 100m;
int quantity = 3;

bool isValid = price > 0 && quantity > 0;

兩個條件:

price > 0
→ true

quantity > 0
→ true

所以:

true && true
↓
true

因此:

isValid = true

|| OR

|| 代表:

只要其中一個條件成立即可。

例如:

bool isFilled = false;
bool isCancelled = true;

bool isFinished = isFilled || isCancelled;

結果:

false || true
↓
true

只要訂單:

已成交
或
已取消

其中一個成立,就可以視為流程已結束。


! NOT

! 會把 bool 反轉。

例如:

bool isMarketOpen = false;

Console.WriteLine(!isMarketOpen);

結果:

True

因為:

false
 ↓ !
true

所以:

!isMarketOpen

可以理解成:

市場不是開盤狀態。


6. Operator Precedence:運算子的優先順序

不同 Operator 有不同的執行順序。

例如:

int result = 10 + 5 * 2;

結果:

20

因為先計算:

5 * 2
↓
10

再計算:

10 + 10
↓
20

如果希望先做加法:

int result = (10 + 5) * 2;

結果:

30

因為括號中的:

10 + 5

會先計算。

目前不需要背所有 Operator 的優先順序。

實務上遇到較複雜的 Expression,可以使用括號清楚表示運算順序,提高可讀性。


7. Condition:讓程式做判斷

目前我們寫的程式大多是:

第一行
 ↓
第二行
 ↓
第三行

一路由上往下執行。

但真正的程式通常需要根據資料決定不同流程。

例如:

訂單是否合法?

市場是否開盤?

訂單金額是否超過限制?

這時就需要: Condition(條件判斷)


8. if

if 的基本語法:

if (condition)
{
    // condition 為 true 時執行
}

其中:

condition

必須是一個結果為:

bool

例如:

decimal total = 1500m;

if (total >= 1000m)
{
    Console.WriteLine("Large Order");
}

這裡:

total >= 1000m

會得到:

true

因此程式會進入 if

Large Order

if 的條件必須是 bool

例如:

bool isMarketOpen = true;

if (isMarketOpen)
{
    Console.WriteLine("Market Open");
}

這是合法的,因為:

isMarketOpen
↓
bool

但下面是不合法的:

int quantity = 10;

if (quantity)
{
}

C# 不會自動把:

10

當成:

true

應該明確寫出條件:

if (quantity > 0)
{
}

因為:

quantity > 0

會得到 bool


9. if / else

如果條件成立與不成立時,需要執行不同內容,可以使用:

if
else

例如:

decimal total = 800m;

if (total >= 1000m)
{
    Console.WriteLine("Large Order");
}
else
{
    Console.WriteLine("Normal Order");
}

結果:

Normal Order

流程:

total >= 1000 ?
      ↓
   true / false
    ↓       ↓
 Large   Normal
 Order   Order

10. else if

如果有多種情況,可以使用:

if
else if
else

例如:

decimal total = 15000m;

if (total >= 20000m)
{
    Console.WriteLine("Level A");
}
else if (total >= 10000m)
{
    Console.WriteLine("Level B");
}
else
{
    Console.WriteLine("Level C");
}

結果:

Level B

if / else if 會:

由上往下依序判斷。

找到第一個成立的條件後,就不會再繼續判斷後面的區塊。

例如:

total = 15000

total >= 20000
↓
false

total >= 10000
↓
true

執行 Level B

因此條件順序很重要。

像這種範圍判斷,通常會從較大的範圍開始:

if (total >= 20000m)
{
    Console.WriteLine("Level A");
}
else if (total >= 10000m)
{
    Console.WriteLine("Level B");
}

11. 搭配 Logical Operator

實際開發時,一個判斷通常不只有一個條件。

例如訂單必須同時符合:

價格 > 0
數量 > 0
市場已開盤

可以寫成:

decimal price = 100m;
int quantity = 5;
bool isMarketOpen = true;

if (price > 0 && quantity > 0 && isMarketOpen)
{
    Console.WriteLine("Order Accepted");
}

這裡:

price > 0
quantity > 0
isMarketOpen

都會產生 bool

接著透過:

&&

把多個條件組合起來。

這就是 Comparison Operator、Logical Operator 與 if 的實際搭配方式。


12. switch

如果要根據同一個值處理多種明確情況,可以使用 switch

例如訂單狀態可能有:

Pending
Filled
Cancelled

可以寫成:

string status = "Filled";

switch (status)
{
    case "Pending":
        Console.WriteLine("Waiting");
        break;

    case "Filled":
        Console.WriteLine("Completed");
        break;

    case "Cancelled":
        Console.WriteLine("Cancelled");
        break;

    default:
        Console.WriteLine("Unknown Status");
        break;
}

結果:

Completed

casedefaultbreak

每個:

case

代表一種可能的值。

例如:

case "Filled":

可以先理解成:

status == "Filled"

符合時,就執行這個 case 裡面的程式。


default 代表:

前面的 case 都沒有符合時執行。

例如:

default:
    Console.WriteLine("Unknown Status");
    break;

而:

break;

表示:

這個 case 處理完成,接著離開 switch。


13. if 還是 switch

兩者都可以做條件判斷,但適合的情境不同。

if

比較適合:

範圍判斷
大小比較
複合條件

例如:

if (price > 0 && quantity > 0)
{
}

switch

比較適合:

根據同一個值
處理多種明確情況

例如:

Pending
Filled
Cancelled
Rejected

所以可以先記成:

範圍或複合條件
↓
if

同一個值有多種情況
↓
switch

這不是絕對規則,但在目前的學習階段很好理解。


14. 實際範例:Order Validation

最後把今天學到的內容組合起來。

decimal price = 250.5m;
int quantity = 5;
bool isMarketOpen = true;

decimal total = price * quantity;

if (price <= 0 || quantity <= 0)
{
    Console.WriteLine("Invalid Order");
}
else if (!isMarketOpen)
{
    Console.WriteLine("Market Closed");
}
else if (total >= 1000m)
{
    Console.WriteLine("Large Order");
}
else
{
    Console.WriteLine("Order Accepted");
}

先計算:

decimal total = price * quantity;

得到:

250.5 × 5
↓
1252.5

接著依序判斷。

第一個條件:

price <= 0 || quantity <= 0

結果:

false

第二個條件:

!isMarketOpen

因為:

isMarketOpen = true

所以:

!true
↓
false

第三個條件:

total >= 1000m

結果:

1252.5 >= 1000
↓
true

因此輸出:

Large Order

整個流程:

Variable
   ↓
Arithmetic Operator
   ↓
計算 total
   ↓
Comparison Operator
   ↓
Logical Operator
   ↓
產生 bool
   ↓
if / else
   ↓
決定程式執行結果

Day 5 小結

今天我們開始讓程式不只是「儲存資料」,而是可以:

計算資料
   ↓
比較資料
   ↓
產生條件結果
   ↓
決定執行方向

Arithmetic Operator

+  -  *  /  %

用來進行數值計算。


Assignment Operator

=
+=
-=
*=
/=

用來設定或更新 Variable 的值。


Comparison Operator

==
!=
>
<
>=
<=

比較後會得到:

bool
↓
true / false

Logical Operator

&&
→ AND

||
→ OR

!
→ NOT

用來組合或反轉條件。


Condition

if
else if
else
switch

讓程式可以根據不同條件,選擇不同的執行流程。


上一篇
Day 4|Variable 與 Type System:變數、型別與資料轉換
下一篇
Day 6|Loop:讓程式重複執行
系列文
現在就學C# 與 ASP.NET Core7
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言